package com.dj.common.web.controller.base;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;


public class BaseController {
	protected Logger logger = LoggerFactory.getLogger(BaseController.class);
	/**
	 * 得到ModelAndView
	 */
	public ModelAndView getModelAndView() {
		return new ModelAndView();
	}
	/**
	 * 得到PageData
	 */
	public Map<String,Object> getParams(){
		Map<String,String[]> properties = this.getRequest().getParameterMap();
		Map<String,Object> returnMap = new HashMap<String,Object>(); 
		Iterator<String> itr = properties.keySet().iterator();
		String name = "";  
		String value = "";  
		while (itr.hasNext()) {
			name = itr.next();
			Object valueObj = properties.get(name);
			if(null == valueObj){
				value = "";
			}else if(valueObj instanceof String[]){ 
				String[] values = (String[])valueObj;
				for(int i=0;i<values.length;i++){ 
					 value = values[i] + ",";
				}
				value = value.substring(0, value.length()-1); 
			}else{
				value = valueObj.toString(); 
			}
			returnMap.put(name, value); 
		}
		return returnMap;
	}

	/**
	 * 得到request对象
	 */
	public HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();

		return request;
	}


	public void writeOut(HttpServletResponse response, String content) {
		try {
			ServletOutputStream out = response.getOutputStream();
			out.write(content.getBytes("UTF-8"));
			out.flush();
			out.close();
		} catch (Exception e) {
		}
	}
}
